﻿#include "crashrpthelper.h"
#include <QCoreApplication>
#include <QDir>
#include <QtDebug>

#ifdef Q_OS_WIN
#include "thirdparty/crashrpt/include/CrashRpt.h"

int CALLBACK CrashCallback(CR_CRASH_CALLBACK_INFO* /*pInfo*/)
{
    return 1;
}
#endif

bool CrashrptHelper::installCrashrpt(const wchar_t* app_name, const wchar_t* app_version,
                                     const wchar_t* log_file_path, const wchar_t* log_file_path2)
{
#ifdef Q_OS_WIN
    QDir app_dir(QCoreApplication::applicationDirPath());
    QString path = app_dir.absolutePath();
    std::wstring ws_path = path.toStdWString();

    CR_INSTALL_INFO info;
#ifdef _UNICODE
    memset(&info, 0, sizeof(CR_INSTALL_INFOW));
    info.cb = sizeof(CR_INSTALL_INFOW);
#else
    memset(&info, 0, sizeof(CR_INSTALL_INFOA));
    info.cb = sizeof(CR_INSTALL_INFOA);
#endif // _UNICODE
    info.pszAppName = app_name;
    info.pszAppVersion = L"1.0.0";
    info.dwFlags = (CR_INST_ALL_POSSIBLE_HANDLERS | CR_INST_HTTP_BINARY_ENCODING);
    info.pszPrivacyPolicyURL = L"http://www.yingce.top";

    info.uPriorities[CR_HTTP] = CR_NEGATIVE_PRIORITY; // Use HTTP.
    info.uPriorities[CR_SMTP] = 1; // Not user SMTP.
    info.uPriorities[CR_SMAPI] = CR_NEGATIVE_PRIORITY; // Not use Simple MAPI.

    info.pszEmailTo = L"6500096@qq.com";
    info.pszSmtpLogin = L"6500096@qq.com";
    info.pszSmtpPassword = L"6768c46fac8e934d8c00";
    info.pszSmtpProxy = L"smtp.qq.com";
    info.pszCrashSenderPath = ws_path.c_str();

    std::wstring email_text(app_name);
    email_text += app_version;
    email_text += L" Crash Report";
    info.pszEmailText = email_text.c_str();

    int ret = crInstall(&info);
    if (0 != ret) {
        qCritical() << "Failed to install crashrpt:" << ret;
        return false;
    }

    crSetCrashCallback(CrashCallback, nullptr);
    crAddScreenshot2(CR_AS_MAIN_WINDOW | CR_AS_USE_JPEG_FORMAT, 95);
    crAddFile2(log_file_path, nullptr, L"Log File", CR_AF_MAKE_FILE_COPY);
    if (log_file_path2) {
        crAddFile2(log_file_path2, nullptr, L"Log File2", CR_AF_MAKE_FILE_COPY);
    }
    return true;
#else
    Q_UNUSED(app_name)
    Q_UNUSED(app_version)
    Q_UNUSED(log_file_path)
    Q_UNUSED(log_file_path2)
    return false;
#endif
}

bool CrashrptHelper::uninstallCrashrpt()
{
#ifdef Q_OS_WIN
    return (0 == crUninstall());
#else
    return false;
#endif
}
